<!--
  省市区街道管理页面 - 降级版本，使用表格代替树形结构
-->
<template>
  <div class="region-management">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <h3>省市区街道管理</h3>
          <div class="buttons">
            <el-button type="primary" @click="handleAddTopLevel">新增省份</el-button>
            <el-button v-if="currentParentId" type="default" @click="goBack">返回上级</el-button>
            <el-button type="success" @click="switchToTreeView">切换到树状视图</el-button>
          </div>
        </div>
      </template>
      
      <div v-if="breadcrumbs.length > 0" class="breadcrumb-container">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item @click="goToRoot">省市区列表</el-breadcrumb-item>
          <el-breadcrumb-item 
            v-for="(item, index) in breadcrumbs" 
            :key="index"
            @click="goToBreadcrumb(index)"
          >
            {{ item.name }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      
      <!-- 使用表格替代树形结构展示 -->
      <el-table 
        v-loading="loading" 
        :data="regionList" 
        style="width: 100%; margin-top: 20px;" 
        border
      >
        <el-table-column prop="name" label="名称" width="180" />
        <el-table-column prop="code" label="编码" width="120" />
        <el-table-column label="级别" width="100">
          <template #default="scope">
            {{ getLevelText(scope.row.level) }}
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="80" />
        <el-table-column v-if="showGeoFields" prop="longitude" label="经度" width="120" />
        <el-table-column v-if="showGeoFields" prop="latitude" label="纬度" width="120" />
        <el-table-column label="操作" fixed="right" width="250">
          <template #default="scope">
            <el-button 
              v-if="scope.row.hasChildren || scope.row.level < 4" 
              type="primary" 
              link 
              @click="handleViewChildren(scope.row)"
            >
              查看子区域
            </el-button>
            <el-button 
              v-if="scope.row.level < 4" 
              type="success" 
              link 
              @click="handleAddChild(scope.row)"
            >
              新增
            </el-button>
            <el-button type="primary" link @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              删除
            </el-button>
            <el-button 
              v-if="scope.row.level === 4" 
              type="info" 
              link 
              @click="showUploadDialog(scope.row)"
            >
              上传图片
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 当前无区域数据的提示 -->
      <div v-if="regionList.length === 0 && !loading" class="empty-tip">
        <el-empty description="暂无区域数据" />
      </div>
    </el-card>
    
    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑区域' : '新增区域'"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="父级区域" v-if="form.parentName">
          <el-input v-model="form.parentName" disabled />
        </el-form-item>
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="区域编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入区域编码" />
        </el-form-item>
        <el-form-item label="级别" prop="level">
          <el-select v-model="form.level" placeholder="请选择级别" disabled style="width: 100%">
            <el-option label="省" :value="1" />
            <el-option label="市" :value="2" />
            <el-option label="区/县" :value="3" />
            <el-option label="街道" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" style="width: 100%" />
        </el-form-item>
        <!-- 只有街道级别才显示经纬度 -->
        <template v-if="form.level === 4">
          <el-form-item label="经度" prop="longitude">
            <el-input-number 
              v-model="form.longitude" 
              :precision="6" 
              :step="0.000001" 
              style="width: 100%" 
              placeholder="请输入经度"
            />
          </el-form-item>
          <el-form-item label="纬度" prop="latitude">
            <el-input-number 
              v-model="form.latitude" 
              :precision="6" 
              :step="0.000001" 
              style="width: 100%" 
              placeholder="请输入纬度"
            />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 上传图片弹窗 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传街道图片"
      width="500px"
    >
      <div v-if="selectedRegion && selectedRegion.imageUrl" class="current-image">
        <h4>当前图片：</h4>
        <el-image 
          :src="selectedRegion.imageUrl"
          style="max-width: 100%; max-height: 200px"
        />
      </div>
      
      <el-upload
        class="upload-demo"
        drag
        action="#"
        :auto-upload="false"
        :limit="1"
        :on-change="handleFileChange"
        :file-list="fileList"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处，或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传JPG/PNG格式图片，大小不超过10MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelUpload">取消</el-button>
          <el-button type="primary" @click="submitUpload">上传</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import axios from '../../utils/axios'
import { useRouter } from 'vue-router'

const router = useRouter()

// 区域列表数据
const regionList = ref([])
const loading = ref(false)
const currentParentId = ref(null)
const breadcrumbs = ref([])

// 是否显示经纬度字段（只对街道级别显示）
const showGeoFields = computed(() => {
  if (!regionList.value || regionList.value.length === 0) return false
  return regionList.value.some(item => item.level === 4)
})

// 选中的区域（用于上传图片等操作）
const selectedRegion = ref(null)

// 新增/编辑弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const form = reactive({
  id: null,
  parentId: null,
  parentName: '',
  name: '',
  code: '',
  level: 1,
  sortOrder: 0,
  longitude: null,
  latitude: null,
  imageUrl: '',
})

// 重置表单
const resetForm = () => {
  form.id = null
  form.parentId = null
  form.parentName = ''
  form.name = ''
  form.code = ''
  form.level = 1
  form.sortOrder = 0
  form.longitude = null
  form.latitude = null
  form.imageUrl = ''
}

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入区域名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入区域编码', trigger: 'blur' },
    { pattern: /^\d{2,20}$/, message: '编码必须为2-20位数字', trigger: 'blur' }
  ],
  sortOrder: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ],
}

// 上传图片相关
const uploadDialogVisible = ref(false)
const fileList = ref([])
const uploadFile = ref(null)

// 初始化
onMounted(() => {
  loadRegionList(null)
})

// 加载区域列表（根据父ID）
const loadRegionList = async (parentId) => {
  loading.value = true
  try {
    const response = await axios.get('/api/regions/list', {
      params: { parentId }
    })
    
    // 简单数据处理，不使用复杂的递归结构
    regionList.value = (response.data || []).map(item => ({
      ...item,
      level: Number(item.level || 1),
      sortOrder: Number(item.sortOrder || 0),
      hasChildren: Boolean(item.hasChildren)
    }))
    
    currentParentId.value = parentId
    
    // 如果有父级，加载面包屑
    if (parentId) {
      loadBreadcrumbs(parentId)
    } else {
      breadcrumbs.value = []
    }
  } catch (error) {
    console.error('加载区域列表失败', error)
    ElMessage.error('加载区域列表失败')
    regionList.value = []
  } finally {
    loading.value = false
  }
}

// 加载面包屑导航数据
const loadBreadcrumbs = async (id) => {
  try {
    const response = await axios.get(`/api/regions/${id}/path`)
    breadcrumbs.value = (response.data || []).map(item => ({
      id: item.id,
      name: item.name,
      level: Number(item.level || 1)
    }))
  } catch (error) {
    console.error('加载面包屑导航失败', error)
    breadcrumbs.value = []
  }
}

// 返回根级
const goToRoot = () => {
  loadRegionList(null)
}

// 通过面包屑导航
const goToBreadcrumb = (index) => {
  if (index >= 0 && index < breadcrumbs.value.length) {
    loadRegionList(breadcrumbs.value[index].id)
  }
}

// 返回上级
const goBack = () => {
  if (breadcrumbs.value.length > 0) {
    // 如果只有一级面包屑，则返回根级
    if (breadcrumbs.value.length === 1) {
      goToRoot()
    } else {
      // 否则返回到上一级面包屑指向的区域
      const parentIndex = breadcrumbs.value.length - 2
      if (parentIndex >= 0) {
        loadRegionList(breadcrumbs.value[parentIndex].id)
      }
    }
  } else {
    goToRoot()
  }
}

// 查看子区域
const handleViewChildren = (row) => {
  loadRegionList(row.id)
}

// 新增顶级区域
const handleAddTopLevel = () => {
  isEdit.value = false
  resetForm()
  form.level = 1
  dialogVisible.value = true
  
  // 清除表单验证
  setTimeout(() => {
    formRef.value?.clearValidate()
  }, 0)
}

// 新增子区域
const handleAddChild = (data) => {
  if (data.level >= 4) {
    ElMessage.warning('街道级别不能再添加子区域')
    return
  }
  
  isEdit.value = false
  resetForm()
  form.parentId = data.id
  form.parentName = data.name
  form.level = data.level + 1
  
  dialogVisible.value = true
  
  // 清除表单验证
  setTimeout(() => {
    formRef.value?.clearValidate()
  }, 0)
}

// 编辑区域
const handleEdit = (data) => {
  isEdit.value = true
  resetForm()
  
  // 复制数据到表单
  form.id = data.id
  form.parentId = data.parentId
  form.name = data.name
  form.code = data.code
  form.level = Number(data.level || 1)
  form.sortOrder = Number(data.sortOrder || 0)
  
  if (data.level === 4) {
    form.longitude = data.longitude !== null && data.longitude !== undefined ? Number(data.longitude) : null
    form.latitude = data.latitude !== null && data.latitude !== undefined ? Number(data.latitude) : null
    form.imageUrl = data.imageUrl || ''
  }
  
  // 如果有父级，获取父级名称
  if (data.parentId) {
    axios.get(`/api/regions/${data.parentId}`)
      .then(res => {
        form.parentName = res.data.name
      })
      .catch(() => {
        form.parentName = '未知'
      })
  }
  
  dialogVisible.value = true
  
  // 清除表单验证
  setTimeout(() => {
    formRef.value?.clearValidate()
  }, 0)
}

// 删除区域
const handleDelete = (data) => {
  ElMessageBox.confirm('确定要删除该区域吗？如果有子区域将无法删除。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await axios.delete(`/api/regions/${data.id}`)
      ElMessage.success('删除成功')
      
      // 刷新当前列表
      loadRegionList(currentParentId.value)
    } catch (error) {
      if (error.response && error.response.data && error.response.data.message) {
        ElMessage.error(error.response.data.message)
      } else {
        ElMessage.error('删除失败，可能该区域下有子区域')
      }
    }
  }).catch(() => {
    // 取消删除
  })
}

// 切换到树状视图
const switchToTreeView = () => {
  router.push('/admin/region-tree')
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 处理表单数据
        const regionData = {
          id: form.id,
          parentId: form.parentId,
          name: form.name,
          code: form.code,
          level: Number(form.level),
          sortOrder: Number(form.sortOrder || 0),
          longitude: null,
          latitude: null,
        }
        
        // 只有街道级别才设置经纬度
        if (form.level === 4) {
          regionData.longitude = form.longitude !== null && form.longitude !== undefined 
            ? Number(form.longitude) : null
          regionData.latitude = form.latitude !== null && form.latitude !== undefined 
            ? Number(form.latitude) : null
        }
        
        // 保存区域
        await axios.post('/api/regions', regionData)
        
        ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
        dialogVisible.value = false
        
        // 刷新当前列表
        loadRegionList(currentParentId.value)
      } catch (error) {
        console.error('保存失败', error)
        if (error.response && error.response.data && error.response.data.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error('保存失败')
        }
      }
    }
  })
}

// 显示上传对话框
const showUploadDialog = (row) => {
  if (!row || row.level !== 4) {
    ElMessage.warning('只有街道级别才能上传图片')
    return
  }
  
  selectedRegion.value = row
  fileList.value = []
  uploadFile.value = null
  uploadDialogVisible.value = true
}

// 处理文件变更
const handleFileChange = (file) => {
  uploadFile.value = file.raw
  
  // 验证文件类型
  const isImage = file.raw.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    fileList.value = []
    return
  }
  
  // 验证文件大小
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    fileList.value = []
    return
  }
}

// 取消上传
const cancelUpload = () => {
  uploadDialogVisible.value = false
  fileList.value = []
  uploadFile.value = null
  selectedRegion.value = null
}

// 提交上传
const submitUpload = async () => {
  if (!uploadFile.value) {
    ElMessage.warning('请先选择要上传的图片')
    return
  }
  
  if (!selectedRegion.value || !selectedRegion.value.id) {
    ElMessage.warning('请先选择一个街道')
    uploadDialogVisible.value = false
    return
  }
  
  try {
    const formData = new FormData()
    formData.append('file', uploadFile.value)
    
    await axios.post(
      `/api/regions/${selectedRegion.value.id}/image`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
    )
    
    ElMessage.success('上传成功')
    uploadDialogVisible.value = false
    
    // 刷新当前列表
    loadRegionList(currentParentId.value)
  } catch (error) {
    console.error('上传失败', error)
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('上传失败')
    }
  }
}

// 获取级别文本
const getLevelText = (level) => {
  // 确保level是数字类型
  const numLevel = parseInt(level, 10)
  
  // 如果转换后不是有效数字，返回未知
  if (isNaN(numLevel)) {
    return '未知'
  }
  
  switch (numLevel) {
    case 1: return '省'
    case 2: return '市'
    case 3: return '区/县'
    case 4: return '街道'
    default: return '未知'
  }
}
</script>

<style scoped>
.region-management {
  height: 100%;
}

.main-card {
  height: calc(100vh - 140px);
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.breadcrumb-container {
  margin-top: 10px;
  margin-bottom: 10px;
}

.empty-tip {
  margin-top: 50px;
  text-align: center;
}

.el-breadcrumb-item {
  cursor: pointer;
}

.current-image {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  padding: 10px;
  border-radius: 4px;
}
</style> 